#include "motor_drv.h"
#include <stdint.h>
#include <stdio.h>
#include "stm32f0xx.h"                  //Device header
#include "stm32f0xx_hal.h"
#include "platform.h"


TIM_HandleTypeDef htim3;
static uint16_t g_motorPwmData[6] = {0, 100, 150, 200, 300, 400};

static void GpioInit(void)
{
	GPIO_InitTypeDef GPIO_InitStruct = {0};

    __HAL_RCC_GPIOC_CLK_ENABLE();

    GPIO_InitStruct.Pin = GPIO_PIN_6;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    GPIO_InitStruct.Alternate = GPIO_AF0_TIM3;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}


static void Tim3Init(void)
{
	__HAL_RCC_TIM3_CLK_ENABLE();
	
	TIM_ClockConfigTypeDef sClockSourceConfig = {0};
	TIM_MasterConfigTypeDef sMasterConfig = {0};
	TIM_OC_InitTypeDef sConfigOC = {0};

	/* USER CODE BEGIN TIM3_Init 1 */

	/* USER CODE END TIM3_Init 1 */
	htim3.Instance = TIM3;
	htim3.Init.Prescaler = 47;
	htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
	htim3.Init.Period = 999;
	htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
	htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
	if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
	{
	Error_Handler();
	}
	sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
	if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
	{
	Error_Handler();
	}
	if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
	{
	Error_Handler();
	}
	sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
	sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
	if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
	{
	Error_Handler();
	}
	sConfigOC.OCMode = TIM_OCMODE_PWM1;
	sConfigOC.Pulse = 0;
	sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
	sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
	if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
	{
	Error_Handler();
	}
	
	HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
	//HAL_TIM_MspPostInit(&htim3);
}



void MotorDrvInit(void)
{
	Tim3Init();
	GpioInit();
}




void MotorPwmDrvTest(void)
{
	#if 0
	for (uint32_t i = 0; i < 500; i += 10)
	{
		__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_3, i); 
		HAL_Delay(50);
	}
	
	for (uint32_t i = 500; i > 0; i -= 10)
	{
		__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_3, i); 
		HAL_Delay(50);
	}
	#endif
	
	
	__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, g_motorPwmData[1] - 1); 
	
}
